<?php
require dirname(dirname(__FILE__)) . '/include/conf.php';
require dirname(dirname(__FILE__)) . '/include/basefunc.php';

// 读取抓数据开关
$errmsg_set = "Open config file error";
$set_str = conf_switch_sets('get');
if ($set_str == 'start'){
	unset($errmsg_set);
}elseif ($set_str == 'stop'){
	$errmsg_set = "Closed switch";
}
if (isset($errmsg_set)){
	print_log($errmsg_set);
}

// 本次抓取时间
if (!isset($argv[1]) || !is_numeric($argv[1])){
	print_log('Parameter error!');
}
$nowtimestamp = (int) $argv[1];
$nowtime = date('Y-m-d H:i:s', $nowtimestamp);

set_time_limit(30); // 超时时间30秒
require dirname(dirname(__FILE__)) . '/include/database.php';


$referer = 'http://msb.188bet.com/zh-cn/mobile/Inplay/LeagueEvents/1';
$url = 'http://msb.188bet.com/zh-cn/Service/OddsService?GetInplayEventDetails&SportId=1&IsFirstLoad=true&Version=0&UiBetType=ftahou&PageNo=1';

$data = request_by_curl_188($url, $referer);

$data = json_decode($data, true);
if (empty($data)){
	// 获取cookie
	request_by_curl_188($referer, $referer);
	$data = request_by_curl_188($url, $referer);
	$data = json_decode($data, true);
}

// ['c']:联赛 ['e']:比赛
// ['o']['ou'] -> [1]盘口 [5]over [7]under
// ['o']['ou1st'] -> [1]盘口 [5]over [7]under
// 大小球特殊盘口说明：2.5/3 = 2.75
$all_match = $teams = $teams_id = array();
if (isset($data['d'])){
	foreach ($data['d'] as $_tmp1){
		if (isset($_tmp1['c'])){
			foreach ($_tmp1['c'] as $_tmp2){
				if (isset($_tmp2['e'])){
					foreach ($_tmp2['e'] as $_tmp3){
						if (!isset($_tmp3['o']['ou'])){
							continue;
						}
						list($match_name) = explode('-', $_tmp2['n']);
						list($home_team) = explode('-', $_tmp3['i'][0]);
						list($visiting_team) = explode('-', $_tmp3['i'][1]);
						
						if (strpos($_tmp2['n'], '特别投注') !== false){
							// 亚洲盘角球
							$wanfa = 2;
						}else {
							// 大小盘
							$wanfa = 4;
						}
							
						$pankou = $_tmp3['o']['ou'][1];
						if (strpos($pankou, '/') !== false){
							$_pankou = explode('/', $pankou);
							$pankou = round(($_pankou[0] + $_pankou[1]) / 2, 2);
						}

						$all_match[] = array(
								'match_id' => $_tmp3['k'],
								'match_name' => $match_name,
								'home_team' => $home_team,
								'visiting_team' => $visiting_team,
								'home_score' => $_tmp3['i'][10],
								'visiting_score' => $_tmp3['i'][11],
								'match_time' => $_tmp3['i'][5],
								'match_id' => $_tmp3['k'],
								'wanfa' => $wanfa,
								'pankou' => $pankou,
								'over_betid' => $_tmp3['o']['ou'][4],
								'over' => $_tmp3['o']['ou'][5],
								'under_betid' => $_tmp3['o']['ou'][6],
								'under' => $_tmp3['o']['ou'][7],
								'fetch_time' => $nowtime,
								'from' => 2,
								'just' => 0,
								'link' => ''
						);
						
						$teams[] = $home_team;
						$teams[] = $visiting_team;
						
					}
				}
			}
		}
	}
}

$teams = array_unique($teams);

$db = db_touzhu();
if (!empty($teams)){
	// 读球队id，预留db中不存在的球队待入库
	$_teams = read_team_id($db, $teams, 2);
	if (!empty($_teams)){
		$teams = array_flip($teams);
		foreach ($_teams as $_team){
			$teams_id[$_team['team']] = $_team['188bet_id'];
			unset($teams[$_team['team']]);
		}
		$teams = array_flip($teams);
	}
	
	// 球队写表
	if (!empty($teams)){
		$_teams_id = write_teams($db, $teams, 2);
		$teams_id = array_merge($teams_id, $_teams_id);
	}
	
	foreach ($all_match as &$_item){
		$_item['home_team_id'] = isset($teams_id[$_item['home_team']]) ? $teams_id[$_item['home_team']] : 0;
		$_item['visiting_team_id'] = isset($teams_id[$_item['visiting_team']]) ? $teams_id[$_item['visiting_team']] : 0;
	}
}

$mem_obj = new Memcache;
$mem_obj->connect("127.0.0.1",  11211);

$time_current = time();

// 判断比赛结束
$mem_all_keys = get_all_mem_keys($mem_obj);
if ($mem_all_keys){
	foreach ($mem_all_keys as $per_mem_key){
		if (strpos($per_mem_key, 'match_id_188_playing_') !== false){
			$mem_re = $mem_obj->get($per_mem_key);
			if ($time_current - $mem_re['timestamp'] >= 86400){
				// 下半场结束(1天没有更新，判定为比赛结束)
				$mem_obj->delete($per_mem_key);
				$_match = get_match_by_id($db, $mem_re['id']);
				up_match_status($db, 4, 6, $_match);
			}
		}
	}
}

if (!empty($all_match)){
	// 写数据库
	$re = write_ball_disc($db, $all_match);
	$re_str = '';
	if (isset($re['succ_match'])){
		$re_str .= 'Write ' . count($re['succ_match']) . ' successful';
		// 记录球赛状态
		foreach ($re['succ_match'] as $match){
			if ($match['wanfa'] != 4){
				continue;
			}
			$mem_key = 'match_id_188_playing_' . $match['match_id'];
			$mem_re = $mem_obj->get($mem_key);
			if ($mem_re){
				if ($match['match_time'] == 'H.T'){
					if ($mem_re['playing_time'] != 'H.T'){
						// 上半场结束
						$_match = get_match_by_id($db, $mem_re['id']);
						$_match['over_betid'] = $match['over_betid'];
						$_match['under_betid'] = $match['under_betid'];
						up_match_status($db, 2, 2, $_match);
						// 中场开始
						up_match_status($db, 2, 3, $match);
					}else {
						// 中场中间
						up_match_status($db, 2, 7, $match, 'noup_noadd');
					}
				}elseif ($mem_re['playing_time'] == 'H.T' && $match['match_time'] != 'H.T'){
					// 中场结束
					$_match = get_match_by_id($db, $mem_re['id']);
					$_match['over_betid'] = $match['over_betid'];
					$_match['under_betid'] = $match['under_betid'];
					up_match_status($db, 3, 4, $_match);
					// 下半场开始
					up_match_status($db, 3, 5, $match);
				}
				$vals = array('playing_time' => $match['match_time'], 'id' => $match['id'], 'timestamp' => $time_current);
				$mem_obj->set($mem_key, $vals, $time_current + 86400 + 3600);
			}else {
				// 上半场开始
				if (!empty($match['pankou']) && $match['over'] > 0 && $match['under'] > 0 && !empty($match['match_time'])){
					up_match_status($db, 1, 1, $match, 'add');
					$vals = array('playing_time' => $match['match_time'], 'id' => $match['id'], 'timestamp' => $time_current);
					$mem_obj->set($mem_key, $vals, $time_current + 86400 + 3600);
				}
				
				/*if ($match['match_time'] > '05:00'){
					// 抓取数据没有从比赛开始开始抓取
				}*/
			}
			
		}
	}
	$mem_obj->close();
	
	if (isset($re['err_match'])){
		$re_str .= (empty($re_str) ? '' : ' &') . 'Write ' . count($re['err_match']) . 'failing';
	}
	print_log($re_str);
}else {
	print_log('No needed ball disc');
}

function get_all_mem_keys($mem_obj, $server = '127.0.0.1:11211'){
	$all_keys = array();
	$all_items = $mem_obj->getExtendedStats('items');
	$item_ids = array_keys($all_items[$server]['items']);
	foreach ($item_ids as $item_id){
		$_keys = $mem_obj->getExtendedStats('cachedump', $item_id, 0);
		$all_keys = array_merge($all_keys, array_keys($_keys[$server]));
	}
	return $all_keys;
}

function up_match_status($db, $status, $type, $match, $match_status = 'up'){
	if ($match){
		if ($match_status == 'up'){
			$sql_status = "update match_status set status={$status}, playing_time='{$match['match_time']}' where `from`=2 and match_id={$match['match_id']}";
		}elseif ($match_status == 'add') {
			$sql_status = "insert into match_status (`from`, competition_id, competition, match_id, home_team_id, visiting_team_id, home_team, visiting_team, playing_time, add_time, status) ";
			$sql_status .= "values(2, 0, '{$match['match_name']}', {$match['match_id']}, {$match['home_team_id']}, {$match['visiting_team_id']}, '{$match['home_team']}', '{$match['visiting_team']}', '{$match['match_time']}', '{$match['fetch_time']}', {$status})";
		}
		if (isset($sql_status)){
			$_re = $db->query($sql_status);
			if (!$_re){
				print_log($sql_status, false);
			}
		}
		
		$sql_add_comp = "insert into half_compare (`from`, type, match_id, playing_time, pankou, over_betid, over, under_betid, under, fetch_time) values";
		$sql_add_comp .= "(2, {$type}, {$match['match_id']}, '{$match['match_time']}', '{$match['pankou']}', '{$match['over_betid']}', '{$match['over']}', '{$match['under_betid']}', '{$match['under']}', '{$match['fetch_time']}')";
		$_re = $db->query($sql_add_comp);
		if (!$_re){
			print_log($sql_add_comp, false);
		}
		return true;
	}else {
		return false;
	}
}
